package pri.damai.xiaowu.usercenter.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * MybatisPlus 全局配置
 *
 * @Desc
 * @Author DaMai
 * @Date 2021/9/28 17:58
 * 但行好事，莫问前程。
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 更新时间
     */
    public static final String UPDATE_TIME_FILED = "updateTime";
    /**
     * 创建时间
     */
    public static final String CREATE_TIME_FILED = "createTime";
    /**
     * 更新人
     */
    public static final String UPDATE_ID_FILED = "updateId";
    /**
     * 创建人
     */
    public static final String CREATE_ID_FILED = "createId";

    /**
     * 新版分页插件
     *
     * @return com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor
     * @apiNote https://baomidou.com/guide/page.html
     * @author DaMai
     * @date 2021/9/28 18:01
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 字段填充。已配置自动填充 createTime、createId、updateTime、updateId 字段的自动填充。
     *
     * @return com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
     * @apiNote https://baomidou.com/guide/auto-fill-metainfo.html
     * @author DaMai
     * @date 2021/9/28 18:11
     */
    @Bean
    public MetaObjectHandler myMetaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                // 起始版本 3.3.0(推荐使用)
                this.strictInsertFill(metaObject, CREATE_TIME_FILED, LocalDateTime.class, LocalDateTime.now());
                this.strictInsertFill(metaObject, CREATE_ID_FILED, Integer.class, getUserId());
                this.strictInsertFill(metaObject, UPDATE_TIME_FILED, LocalDateTime.class, LocalDateTime.now());
                this.strictInsertFill(metaObject, UPDATE_ID_FILED, Integer.class, getUserId());
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                // 起始版本 3.3.0(推荐)
                this.strictUpdateFill(metaObject, UPDATE_TIME_FILED, LocalDateTime.class, LocalDateTime.now());
                this.strictUpdateFill(metaObject, UPDATE_ID_FILED, Integer.class, getUserId());
            }
        };
    }

    //TODO 待集成网关进行替换
    private Integer getUserId() {
        //Integer localUserId = ThreadLocalUserUtils.getLocalUserId();
        return 1;
    }
}
